package byx.container.extension.aop;

import byx.container.annotation.annotation.AnnotatedBy;
import byx.container.annotation.annotation.Register;
import byx.container.extension.aop.annotation.Enhance;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Pattern;

@Register
public class AdviceManager {
    private final List<Object> advices;

    public AdviceManager(@AnnotatedBy(Enhance.class) List<Object> advices) {
        this.advices = advices;
    }

    public List<Object> getAdvices(Class<?> type) {
        List<Object> result = new ArrayList<>();
        for (Object advice : advices) {
            Enhance enhance = advice.getClass().getAnnotation(Enhance.class);
            if (match(type, enhance)) {
                result.add(advice);
            }
        }
        return result;
    }

    private boolean match(Class<?> type, Enhance enhance) {
        if (Arrays.stream(enhance.value()).anyMatch(type::isAssignableFrom)) {
            return true;
        }

        String regex = enhance.pattern();
        if ("".equals(regex)) {
            return false;
        }

        regex = "^(.*)" + regex + "(.*)$";
        return Pattern.matches(regex, type.getName());
    }
}
